# -*- coding: utf-8 -*-
"""
悬浮窗模块
提供悬浮窗UI操作功能
"""

import tkinter as tk
from tkinter import ttk
import threading
import time

# 主题配色
COLORS = {
    'bg_primary': '#0a0a0a',      # 玄青黑
    'bg_secondary': '#1a1a1a',    # 深灰
    'bg_tertiary': '#2a2a2a',     # 中灰
    'accent_gold': '#FFD700',     # 鎏金
    'accent_red': '#E53A3A',      # 血月红
    'text_primary': '#FFFFFF',    # 主文字
    'text_secondary': '#CCCCCC',  # 次要文字
    'text_muted': '#888888',      # 暗淡文字
    'success': '#4CAF50',         # 成功绿
    'warning': '#FF9800',         # 警告橙
    'error': '#F44336'            # 错误红
}

class FloatingWindow:
    """悬浮窗类"""
    
    def __init__(self, parent_app):
        self.parent_app = parent_app
        self.window = None
        self.is_visible = False
        self.is_dragging = False
        self.drag_start_x = 0
        self.drag_start_y = 0
        self.auto_hide_timer = None
        self.auto_hide_delay = 3000  # 3秒后自动隐藏
        
        # 悬浮窗位置
        self.x = 100
        self.y = 100
        
    def create_floating_window(self):
        """创建悬浮窗"""
        if self.window:
            return
            
        self.window = tk.Toplevel()
        self.window.title("操作面板")
        self.window.geometry(f"200x120+{self.x}+{self.y}")
        
        # 设置窗口属性
        self.window.overrideredirect(True)  # 无边框
        self.window.attributes('-topmost', True)  # 置顶
        self.window.attributes('-alpha', 0.9)  # 半透明
        self.window.configure(bg=COLORS['bg_secondary'])
        
        # 设置样式
        self.setup_styles()
        
        # 创建UI组件
        self.create_floating_widgets()
        
        # 绑定事件
        self.bind_events()
        
        self.is_visible = True
        
        # 启动自动隐藏定时器
        self.start_auto_hide_timer()
        
    def setup_styles(self):
        """设置悬浮窗样式"""
        style = ttk.Style()
        
        # 悬浮窗按钮样式
        style.configure('Float.TButton',
                       background=COLORS['bg_tertiary'],
                       foreground=COLORS['text_primary'],
                       borderwidth=1,
                       relief='solid',
                       font=('Microsoft YaHei UI', 8),
                       padding=(5, 2))
        
        style.map('Float.TButton',
                 background=[('active', COLORS['accent_gold']),
                           ('pressed', COLORS['accent_gold'])],
                 foreground=[('active', COLORS['bg_primary']),
                           ('pressed', COLORS['bg_primary'])])
        
        # 录制按钮样式
        style.configure('FloatRecord.TButton',
                       background=COLORS['accent_red'],
                       foreground=COLORS['text_primary'],
                       borderwidth=1,
                       relief='solid',
                       font=('Microsoft YaHei UI', 8),
                       padding=(5, 2))
        
        # 播放按钮样式
        style.configure('FloatPlay.TButton',
                       background=COLORS['success'],
                       foreground=COLORS['text_primary'],
                       borderwidth=1,
                       relief='solid',
                       font=('Microsoft YaHei UI', 8),
                       padding=(5, 2))
        
    def create_floating_widgets(self):
        """创建悬浮窗UI组件"""
        # 主框架
        main_frame = tk.Frame(self.window, bg=COLORS['bg_secondary'], padx=5, pady=5)
        main_frame.pack(fill='both', expand=True)
        
        # 标题栏（用于拖拽）
        title_frame = tk.Frame(main_frame, bg=COLORS['bg_primary'], height=20)
        title_frame.pack(fill='x', pady=(0, 5))
        title_frame.pack_propagate(False)
        
        title_label = tk.Label(title_frame, text="🎯 操作面板", 
                              bg=COLORS['bg_primary'], fg=COLORS['text_primary'],
                              font=('Microsoft YaHei UI', 8, 'bold'))
        title_label.pack(side='left', padx=5, pady=2)
        
        # 关闭按钮
        close_btn = tk.Label(title_frame, text="✕", 
                            bg=COLORS['bg_primary'], fg=COLORS['accent_red'],
                            font=('Microsoft YaHei UI', 8, 'bold'),
                            cursor='hand2')
        close_btn.pack(side='right', padx=5, pady=2)
        close_btn.bind('<Button-1>', self.hide_floating_window)
        
        # 绑定标题栏拖拽事件
        title_frame.bind('<Button-1>', self.start_drag)
        title_frame.bind('<B1-Motion>', self.on_drag)
        title_frame.bind('<ButtonRelease-1>', self.stop_drag)
        title_label.bind('<Button-1>', self.start_drag)
        title_label.bind('<B1-Motion>', self.on_drag)
        title_label.bind('<ButtonRelease-1>', self.stop_drag)
        
        # 按钮区域
        button_frame = tk.Frame(main_frame, bg=COLORS['bg_secondary'])
        button_frame.pack(fill='both', expand=True)
        
        # 第一行按钮
        row1_frame = tk.Frame(button_frame, bg=COLORS['bg_secondary'])
        row1_frame.pack(fill='x', pady=2)
        
        # 录制按钮
        self.float_record_btn = ttk.Button(row1_frame, text="🎬 录制", 
                                          command=self.toggle_recording,
                                          style='FloatRecord.TButton')
        self.float_record_btn.pack(side='left', padx=2, fill='x', expand=True)
        
        # 播放按钮
        self.float_play_btn = ttk.Button(row1_frame, text="▶️ 播放", 
                                        command=self.play_script,
                                        style='FloatPlay.TButton')
        self.float_play_btn.pack(side='right', padx=2, fill='x', expand=True)
        
        # 第二行按钮
        row2_frame = tk.Frame(button_frame, bg=COLORS['bg_secondary'])
        row2_frame.pack(fill='x', pady=2)
        
        # 停止按钮
        self.float_stop_btn = ttk.Button(row2_frame, text="⏹️ 停止", 
                                        command=self.stop_all,
                                        style='Float.TButton')
        self.float_stop_btn.pack(side='left', padx=2, fill='x', expand=True)
        
        # 主窗口按钮
        self.float_main_btn = ttk.Button(row2_frame, text="🏠 主窗口", 
                                        command=self.show_main_window,
                                        style='Float.TButton')
        self.float_main_btn.pack(side='right', padx=2, fill='x', expand=True)
        
        # 更新按钮状态
        self.update_button_states()
        
    def bind_events(self):
        """绑定窗口事件"""
        # 鼠标进入和离开事件
        self.window.bind('<Enter>', self.on_mouse_enter)
        self.window.bind('<Leave>', self.on_mouse_leave)
        
        # 绑定所有子组件的鼠标事件
        def bind_recursive(widget):
            widget.bind('<Enter>', self.on_mouse_enter)
            widget.bind('<Leave>', self.on_mouse_leave)
            for child in widget.winfo_children():
                bind_recursive(child)
        
        bind_recursive(self.window)
        
    def start_drag(self, event):
        """开始拖拽"""
        self.is_dragging = True
        self.drag_start_x = event.x_root - self.window.winfo_x()
        self.drag_start_y = event.y_root - self.window.winfo_y()
        
    def on_drag(self, event):
        """拖拽中"""
        if self.is_dragging:
            x = event.x_root - self.drag_start_x
            y = event.y_root - self.drag_start_y
            self.window.geometry(f"+{x}+{y}")
            self.x = x
            self.y = y
            
    def stop_drag(self, event):
        """停止拖拽"""
        self.is_dragging = False
        
    def on_mouse_enter(self, event):
        """鼠标进入悬浮窗"""
        self.cancel_auto_hide_timer()
        
    def on_mouse_leave(self, event):
        """鼠标离开悬浮窗"""
        # 检查鼠标是否真的离开了窗口区域
        x, y = self.window.winfo_pointerxy()
        wx, wy = self.window.winfo_rootx(), self.window.winfo_rooty()
        ww, wh = self.window.winfo_width(), self.window.winfo_height()
        
        if not (wx <= x <= wx + ww and wy <= y <= wy + wh):
            self.start_auto_hide_timer()
            
    def start_auto_hide_timer(self):
        """启动自动隐藏定时器"""
        self.cancel_auto_hide_timer()
        self.auto_hide_timer = self.window.after(self.auto_hide_delay, self.auto_hide)
        
    def cancel_auto_hide_timer(self):
        """取消自动隐藏定时器"""
        if self.auto_hide_timer:
            self.window.after_cancel(self.auto_hide_timer)
            self.auto_hide_timer = None
            
    def auto_hide(self):
        """自动隐藏悬浮窗"""
        self.hide_floating_window()
        
    def show_floating_window(self):
        """显示悬浮窗"""
        if not self.window:
            self.create_floating_window()
        else:
            self.window.deiconify()
            self.window.lift()
            self.is_visible = True
            self.update_button_states()
            self.start_auto_hide_timer()
            
    def hide_floating_window(self, event=None):
        """隐藏悬浮窗"""
        if self.window:
            self.window.withdraw()
            self.is_visible = False
            self.cancel_auto_hide_timer()
            
    def destroy_floating_window(self):
        """销毁悬浮窗"""
        if self.window:
            self.cancel_auto_hide_timer()
            self.window.destroy()
            self.window = None
            self.is_visible = False
            
    def toggle_floating_window(self):
        """切换悬浮窗显示状态"""
        if self.is_visible:
            self.hide_floating_window()
        else:
            self.show_floating_window()
            
    def update_button_states(self):
        """更新按钮状态"""
        if not self.window:
            return
            
        # 根据主程序状态更新按钮
        if hasattr(self.parent_app, 'is_recording'):
            if self.parent_app.is_recording:
                self.float_record_btn.config(text="⏹️ 停止录制")
            else:
                self.float_record_btn.config(text="🎬 开始录制")
                
        if hasattr(self.parent_app, 'is_playing'):
            if self.parent_app.is_playing:
                self.float_play_btn.config(state='disabled')
                self.float_stop_btn.config(state='normal')
            else:
                self.float_play_btn.config(state='normal')
                self.float_stop_btn.config(state='disabled')
                
    def toggle_recording(self):
        """切换录制状态"""
        self.parent_app.toggle_recording()
        self.update_button_states()
        
    def play_script(self):
        """播放脚本"""
        self.parent_app.play_script()
        self.update_button_states()
        
    def stop_all(self):
        """停止所有操作"""
        if hasattr(self.parent_app, 'is_recording') and self.parent_app.is_recording:
            self.parent_app.stop_recording()
        if hasattr(self.parent_app, 'is_playing') and self.parent_app.is_playing:
            self.parent_app.stop_playing()
        self.update_button_states()
        
    def show_main_window(self):
        """显示主窗口"""
        if hasattr(self.parent_app, 'show_window'):
            self.parent_app.show_window()
        else:
            self.parent_app.root.deiconify()
            self.parent_app.root.lift()
            self.parent_app.root.focus_force()
            
    def set_position(self, x, y):
        """设置悬浮窗位置"""
        self.x = x
        self.y = y
        if self.window:
            self.window.geometry(f"+{x}+{y}")
            
    def get_position(self):
        """获取悬浮窗位置"""
        if self.window:
            return self.window.winfo_x(), self.window.winfo_y()
        return self.x, self.y